package cn.itcast.nio.c4;

import cn.itcast.nio.c2.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class MultiThreadServer01 {
    public static void main(String[] args) throws IOException {
        //boss线程
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        //boss线程配合selector
        Selector bossSelector = Selector.open();
        SelectionKey bossKey = ssc.register(bossSelector, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT); //监听ACCEPT
        ssc.bind(new InetSocketAddress(8080));

        //创建固定数量的Worker
        Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-" + i);
        }

        AtomicInteger index = new AtomicInteger();
        while (true) {
            bossSelector.select();
            Iterator<SelectionKey> iter = bossSelector.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isAcceptable()) { //1. boss线程处理accept事件
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("connected----{}", sc.getRemoteAddress());

                    log.debug("before register----{}", sc.getRemoteAddress());
                    // 2 关联 selector
                    int roundIndex = index.getAndIncrement() % workers.length;
                    workers[roundIndex].register(sc);
                    log.debug("after register----{}", sc.getRemoteAddress());
                }
            }
        }
    }

    static class Worker implements Runnable {
        private Thread thread; //线程
        private Selector selector; // 选择器
        private String name; //线程名
        private volatile boolean start = false;//是否初始化过

        public Worker(String name) {
            this.name = name;
        }


        /**
         * 初始化Thread和Selector(只会执行一次) 要保证register()先执行，再执行.select()
         *
         * @param sc 此方法在boss线程执行
         * @throws IOException
         */
        public void register(SocketChannel sc) throws IOException {
            if (!start) {
                selector = Selector.open();//在前防止空指针
                thread = new Thread(this, name);
                thread.start();//启动线程
                start = true;
            }
            selector.wakeup(); //唤醒select（中断select()的阻塞状态）
            sc.register(selector, SelectionKey.OP_READ, null);//关注可读事件

        }

        /**
         * worker线程执行
         */
        @Override
        public void run() {
            while (true) {
                try {
                    selector.select();
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        iter.remove();
                        if (key.isReadable()) { //worker处理可读事件
                            SocketChannel channel = (SocketChannel) key.channel();
                            try {
                                ByteBuffer buffer = ByteBuffer.allocate(16);
                                log.debug("read ----{}", channel.getRemoteAddress());
                                int read = channel.read(buffer);
                                if (read > 0) {
                                    buffer.flip();
                                    ByteBufferUtil.debugAll(buffer);
                                } else {
                                    log.debug("客户端正常断开：{} ", channel.getRemoteAddress());
                                    key.cancel();
                                }
                            } catch (IOException e) {
                                log.error("客户端异常断开：{} ", channel.getRemoteAddress());
                                key.cancel();
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
